<?php

require_once '../application/business/ClientBusiness.php';
require_once '../application/business/TransactionBusiness.php';
require_once 'PagSeguroLibrary/PagSeguroLibrary.php';
require_once 'Zend/Application.php';
require_once 'Zend/Db.php';
require_once 'Zend/Db/Table.php';

class CronJobBusiness{

	public function updateTransaction(){

		try{

			echo "Atualizando transações...\n";

			$credentials = new PagSeguroAccountCredentials("pg.gorla@gmail.com", "38EDF6B4BBEB4848A39B8433753463AA");

			$dbhost="localhost";
			$dbuser="root";
			$dbpasswd="";
			$dbname="carmezin_project";
			$conexao = @mysql_pconnect($dbhost, $dbuser, $dbpasswd) or die ("Não foi possível conectar-se ao servidor MySQL");
			$db = @mysql_select_db($dbname) or die ("Não foi possível selecionar o banco de dados <b>$dbname</b>");

			$consulta=mysql_query("SELECT id_transaction FROM cl_transaction");


			$all = array();
			while ($all[] = mysql_fetch_assoc($consulta)) {
			}

			$i = 1;
			foreach ($all as $transaction) {
				$transact = PagSeguroTransactionSearchService::searchByCode(
				$credentials,
				$transaction['id_transaction']
				);

				$query=mysql_query("SELECT * FROM cl_transaction ct WHERE ct.id_transaction = '".$transaction['id_transaction']."'");

				$result = mysql_fetch_array($query);

				if($result != null){

					$data = array(
					'date'				=> $transact->getDate(),
					'status'			=> $transact->getStatus()->getValue(),
					'grossAmount' 		=> $transact->getGrossAmount(),
					'netAmount'			=> $transact->getNetAmount(),
					'discountAmount'	=> $transact->getDiscountAmount(),
					'feeAmount'			=> $transact->getFeeAmount(),
					'extraAmount'		=> $transact->getExtraAmount(),
					'shippingCost'		=> $transact->getShipping()->getCost(),
					);


					$query = "UPDATE cl_transaction SET
					date_update='".$transact->getLastEventDate()."', 
					status=".$transact->getStatus()->getValue().", 
					grossAmount=".$transact->getGrossAmount().", 
					netAmount=".$transact->getNetAmount().", 
					discountAmount=".$transact->getDiscountAmount().", 
					feeAmount=".$transact->getFeeAmount().", 
					extraAmount=".$transact->getExtraAmount().", 
					shippingCost=".$transact->getShipping()->getCost()." 
					WHERE id_transaction='".$transaction['id_transaction']."'";

					$update=mysql_query($query);

					echo $i." ".$transaction['id_transaction']." Atualizada com sucesso!\n";

					++$i;
				}

			}

			echo "Transações atualizadas com sucesso\n";
			echo "";
		}catch (Exception $e){
		}
	}

	public function seacrhTransaction(){

		$transactionBusiness = new TransactionBusiness();

		try{

			echo "Buscando transações...\n";

			$credentials = new PagSeguroAccountCredentials("pg.gorla@gmail.com", "38EDF6B4BBEB4848A39B8433753463AA");

			$dbhost="localhost";
			$dbuser="root";
			$dbpasswd="";
			$dbname="carmezin_project";
			$conexao = @mysql_pconnect($dbhost, $dbuser, $dbpasswd) or die ("Não foi possível conectar-se ao servidor MySQL");
			$db = @mysql_select_db($dbname) or die ("Não foi possível selecionar o banco de dados <b>$dbname</b>");

			$initial_date = date("Y-m-d\TH:i", strtotime("-30 days"));

			$final_date = date("Y-m-d\TH:i");

			$maxPageResults = 100;

			$pageNumber = 1;

			LogPagSeguro::info("Preparando para atualização transações por data");
			//Realizando a consulta das transações por data
			$result = PagSeguroTransactionSearchService::searchByDate(
			$credentials,
			$pageNumber,
			$maxPageResults,
			$initial_date,
			$final_date
			);

			$transactions = $result->getTransactions();

			foreach ($transactions as $transaction) {
				

			try{
				LogPagSeguro::info("Iniciando transação ".$transaction->getCode()."por data");
				$transact = PagSeguroTransactionSearchService::searchByCode(
				$credentials,
				$transaction->getCode()
				);

				$query=mysql_query("SELECT * FROM cl_transaction ct WHERE ct.id_transaction = '".$transaction->getCode()."'");

				$oldTransaction = mysql_fetch_array($query);

				if($oldTransaction){

					$data = array(
					'date'				=> $transact->getDate(),
					'status'			=> $transact->getStatus()->getValue(),
					'grossAmount' 		=> $transact->getGrossAmount(),
					'netAmount'			=> $transact->getNetAmount(),
					'discountAmount'	=> $transact->getDiscountAmount(),
					'feeAmount'			=> $transact->getFeeAmount(),
					'extraAmount'		=> $transact->getExtraAmount(),
					'shippingCost'		=> $transact->getShipping()->getCost(),
					);
					

					$query = "UPDATE cl_transaction SET
					date_update='".$transact->getLastEventDate()."', 
					status=".$transact->getStatus()->getValue().", 
					grossAmount=".$transact->getGrossAmount().", 
					netAmount=".$transact->getNetAmount().", 
					discountAmount=".$transact->getDiscountAmount().", 
					feeAmount=".$transact->getFeeAmount().", 
					extraAmount=".$transact->getExtraAmount().", 
					shippingCost=".$transact->getShipping()->getCost()." 
					WHERE id_transaction='".$transaction->getCode()."'";

					$update=mysql_query($query);
					LogPagSeguro::info("Transação ".$transaction->getCode()." atualizada com sucesso");

				}else{

					$query = mysql_query("SELECT * FROM cl_client cc INNER JOIN cl_address ca on ca.id_client = cc.id_client WHERE cc.email = '".$transact->getSender()->getEmail()."'");

					$client = mysql_fetch_array($query);
					
					$payment = array(
					'id_transaction' => $transaction->getCode(),
					'id_payment' => $transact->getPaymentMethod()->getCode()->getValue(), 
					);
					
					$data_query = "INSERT INTO cl_transaction VALUES(
					id_transaction='".$transact->getCode()."', 
					id_client='".$client["id_client"]."', 
					date='".$transact->getDate()."', 
					date_update='".$transact->getLastEventDate()."', 
					status=".$transact->getStatus()->getValue().", 
					grossAmount=".$transact->getGrossAmount().", 
					netAmount=".$transact->getNetAmount().", 
					discountAmount=".$transact->getDiscountAmount().", 
					feeAmount=".$transact->getFeeAmount().", 
					extraAmount=".$transact->getExtraAmount().", 
					shippingCost=".$transact->getShipping()->getCost().")";
					
					echo $data_query;
					
					mysql_query($data_query);

					$transactionBusiness->newTransaction($data);

					$transactionBusiness->savePaymentType($payment);

					foreach ($transact->getItems() as $item){
						$dataProd = array(
					'id_transaction' => $transaction->getCode(),
					'id_product' => $item->getId(),
						);

						$cartMirror = array(
					'id_transaction' => $transaction->getCode(),
					'id_product' => $item->getId(),
					'id_client' => $client['id_client'],
					'qtd' => $item->getQuantity(),
						);

						$transactionBusiness->saveProducts($dataProd);

						$transactionBusiness->saveCartMirror($cartMirror);
					}

					LogPagSeguro::info("Transação ".$transaction->getCode()." recebida com sucesso");
				}
				LogPagSeguro::info("Finalizando transação ".$transaction->getCode());
			}catch (Exception $e){
					
			}
			}

			echo "Transações atualizadas com sucesso\n";
			echo "";
		}catch (Exception $e){
		}


	}
}